<template>
  <div 
    id="influencer-trail-panel" 
    class="influencer-trail-panel"
    :class="{ active: isActive && !controlsHidden }"
  >
    <div class="influencer-header">
      <div class="influencer-title">达人足迹</div>
      <button 
        id="upload-media-btn" 
        class="upload-media-btn"
        @click="showUploadModal"
        title="上传图片/视频"
      >
        <i class="fas fa-upload"></i>
      </button>
      <button 
        id="close-influencer-trail" 
        class="close-influencer"
        @click="toggleInfluencerTrail"
        title="关闭"
      >
        <i class="fas fa-times"></i>
      </button>
    </div>
    
    <!-- 上传表单模态框 -->
    <div 
      id="upload-modal" 
      class="upload-modal-overlay"
      :class="{ active: uploadModalVisible }"
    >
      <div class="upload-modal">
        <div class="upload-modal-header">
          <h3 class="upload-modal-title">上传您的足迹</h3>
          <button 
            id="close-upload-modal" 
            class="close-influencer"
            @click="hideUploadModal"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="upload-modal-body">
          <div class="upload-input-group">
              <label for="media-file" class="upload-label">选择图片/视频:</label>
              <!-- 使用label标签包裹整个上传区域，这是HTML原生的触发文件选择的可靠方式 -->
              <label for="media-file" class="file-upload-area">
                <input 
                  type="file" 
                  id="media-file" 
                  class="file-upload-input"
                  accept="image/*,video/*"
                  @change="handleFileSelection"
                >
                <div class="file-upload-icon">
                  <i class="fas fa-cloud-upload-alt"></i>
                </div>
                <p class="file-upload-text">点击或拖拽文件到此处上传</p>
                <p class="file-upload-subtext">支持JPG、PNG、GIF、MP4格式</p>
              </label>
            <div id="file-preview" class="file-preview" v-if="filePreviewUrl">
              <img 
                v-if="isImageFile" 
                :src="filePreviewUrl" 
                class="preview-image"
                :alt="'预览'"
              >
              <video 
                v-else-if="isVideoFile" 
                :src="filePreviewUrl" 
                class="preview-video"
                controls
              ></video>
            </div>
          </div>
          <div class="upload-input-group">
            <label for="media-description" class="upload-label">添加描述:</label>
            <textarea 
              id="media-description" 
              rows="3" 
              class="upload-textarea"
              placeholder="分享您的体验..."
              v-model="mediaDescription"
            ></textarea>
          </div>
          <div 
            id="upload-status" 
            class="upload-status"
            :class="uploadStatus.type"
            v-if="uploadStatus.message"
          >
            {{ uploadStatus.message }}
          </div>
        </div>
        <div class="upload-modal-buttons">
          <button 
            id="cancel-upload" 
            class="upload-cancel-btn"
            @click="hideUploadModal"
            :disabled="uploading"
          >
            取消
          </button>
          <button 
            id="submit-upload" 
            class="upload-submit-btn"
            @click="handleUploadSubmit"
            :disabled="!selectedFile || !mediaDescription.trim() || uploading"
          >
            {{ uploading ? '上传中...' : '上传' }}
          </button>
        </div>
      </div>
    </div>
    
    <div class="influencer-content" id="influencer-trail-content">
      <div v-if="loading" class="loading-container">
        <i class="fas fa-spinner fa-spin fa-2x"></i>
        <p>加载中...</p>
      </div>
      <div v-else-if="influencerTrails.length === 0" class="empty-container">
        <i class="fas fa-camera fa-3x"></i>
        <p>暂无达人足迹，快来上传您的体验吧！</p>
        <button class="influencer-upload-btn" @click="showUploadModal">
          <i class="fas fa-upload"></i>
          上传第一个足迹
        </button>
      </div>
      <div v-else class="influencer-list">
        <div 
          v-for="trail in influencerTrails" 
          :key="trail.id"
          class="influencer-item"
        >
          <div class="influencer-info">
            <div class="avatar-container">
              <img 
                v-if="trail.influencerAvatar" 
                :src="trail.influencerAvatar" 
                class="influencer-avatar" 
                :alt="trail.influencerName || '用户'"
              >
              <div v-else class="influencer-avatar-placeholder">
                <i class="fas fa-user"></i>
              </div>
            </div>
            <div class="influencer-details">
              <div class="influencer-name">{{ trail.influencerName || '游客' }}</div>
              <div class="influencer-meta">
                <span class="trail-time">{{ formatTime(trail.createTime) }}</span>
              </div>
            </div>
          </div>
          <div class="influencer-trail-content">
            {{ trail.description || '' }}
          </div>
          <div class="influencer-media">
            <div v-if="trail.mediaType === 'image' || !trail.mediaType" class="influencer-media-item">
              <img 
                :src="trail.mediaUrl"
                class="influencer-media-img"
                :alt="trail.description || '达人足迹'"
              >
            </div>
            <div v-else-if="trail.mediaType === 'video'" class="influencer-media-item video">
              <video 
                :src="trail.mediaUrl"
                class="influencer-media-video"
                controls
              ></video>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="influencer-pagination">
      <button 
        id="influencer-prev-page" 
        class="influencer-page-btn"
        :disabled="currentPage === 1 || loading"
        @click="showPreviousInfluencerPage"
        title="上一页"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span id="influencer-page-info" class="influencer-page-info">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </span>
      <button 
        id="influencer-next-page" 
        class="influencer-page-btn"
        :disabled="currentPage === totalPages || loading"
        @click="showNextInfluencerPage"
        title="下一页"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue'
import { influencerAPI, fileAPI } from '../services/api.js'

export default {
  name: 'InfluencerTrail',
  props: {
    pointId: {
      type: String,
      default: null
    },
    controlsHidden: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    // 状态管理
    const isActive = ref(false)
    const influencerTrails = ref([])
    const currentPage = ref(1)
    const pageSize = ref(5)
    const totalItems = ref(0)
    const loading = ref(false)
    
    // 上传相关状态
    const uploadModalVisible = ref(false)
    const selectedFile = ref(null)
    const filePreviewUrl = ref('')
    const mediaDescription = ref('')
    const uploading = ref(false)
    const uploadStatus = ref({
      type: '', // success, error, info
      message: ''
    })

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(totalItems.value / pageSize.value)
    })

    // 计算文件类型
    const isImageFile = computed(() => {
      if (!selectedFile.value) return false
      return selectedFile.value.type.startsWith('image/')
    })

    const isVideoFile = computed(() => {
      if (!selectedFile.value) return false
      return selectedFile.value.type.startsWith('video/')
    })

    // 格式化时间
    const formatTime = (timeString) => {
      if (!timeString) return ''
      const date = new Date(timeString)
      const now = new Date()
      const diffTime = Math.abs(now - date)
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 0) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else if (diffDays === 1) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else if (diffDays < 7) {
        return diffDays + '天前'
      } else {
        return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
      }
    }

    // 加载达人足迹
    const loadInfluencerTrails = async (reset = false) => {
      if (!props.pointId) {
        return
      }

      if (loading.value) {
        return
      }

      loading.value = true

      try {
        if (reset) {
          currentPage.value = 1
        }

        const response = await influencerAPI.getInfluencerTrails(
          props.pointId,
          currentPage.value,
          pageSize.value
        )

        // 处理返回的数据
        if (response && response.code === 200 && response.rows) {
          influencerTrails.value = response.rows
          totalItems.value = response.total || 0
        } else {
          influencerTrails.value = []
          totalItems.value = 0
        }
      } catch (error) {
        console.error('加载达人足迹失败:', error)
        influencerTrails.value = []
        totalItems.value = 0
      } finally {
        loading.value = false
      }
    }

    // 现在使用HTML原生的label标签方式触发文件选择，不需要额外的方法
    // 点击label内的任何区域都会自动触发与其关联的input元素的点击事件

    // 处理文件选择
    const handleFileSelection = (event) => {
      const file = event.target.files[0]
      if (!file) {
        selectedFile.value = null
        filePreviewUrl.value = ''
        return
      }

      selectedFile.value = file
      
      // 创建预览URL
      const objectUrl = URL.createObjectURL(file)
      filePreviewUrl.value = objectUrl
      
      // 清除之前的状态
      uploadStatus.value = {
        type: '',
        message: ''
      }
    }

    // 处理上传提交
    const handleUploadSubmit = async () => {
      if (!selectedFile.value || !mediaDescription.value.trim() || !props.pointId || uploading.value) {
        return
      }

      uploading.value = true
      uploadStatus.value = {
        type: 'info',
        message: '正在上传...'
      }

      try {
        // 先使用fileAPI.uploadMedia上传文件到服务器
        uploadStatus.value = {
          type: 'info',
          message: '正在上传文件...'
        }
        
        // 调用实际的文件上传API
        const fileUploadResponse = await fileAPI.uploadMedia(selectedFile.value)
        
        if (!fileUploadResponse || fileUploadResponse.code !== 200 || !fileUploadResponse.data) {
          throw new Error('文件上传失败：' + (fileUploadResponse?.msg || '未知错误'))
        }
        
        // 获取上传后的文件URL，并清理字符串中的反引号和空格
        const mediaUrl = fileUploadResponse.data.replace(/[`\s]/g, '').trim()
        const mediaType = selectedFile.value.type.startsWith('image/') ? 'image' : 'video'
        
        uploadStatus.value = {
          type: 'info',
          message: '正在保存足迹信息...'
        }
        
        // 然后提交达人足迹信息
        const response = await influencerAPI.uploadInfluencerTrail(
          props.pointId,
          mediaUrl,
          mediaType,
          mediaDescription.value.trim()
        )

        // 假设成功后，重置表单并重新加载数据
        if (response && response.code === 200) {
          uploadStatus.value = {
            type: 'success',
            message: '上传成功！'
          }
          
          // 重置表单
          selectedFile.value = null
          filePreviewUrl.value = ''
          mediaDescription.value = ''
          
          // 关闭模态框
          setTimeout(() => {
            hideUploadModal()
          }, 1500)
          
          // 重新加载达人足迹
          loadInfluencerTrails(true)
        } else {
          throw new Error(response.msg || '上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        uploadStatus.value = {
          type: 'error',
          message: '上传失败：' + error.message
        }
      } finally {
        uploading.value = false
      }
    }

    // 显示上传模态框
    const showUploadModal = () => {
      if (!props.pointId) {
        alert('请先选择一个VR点')
        return
      }
      uploadModalVisible.value = true
      uploadStatus.value = {
        type: '',
        message: ''
      }
    }

    // 隐藏上传模态框
    const hideUploadModal = () => {
      uploadModalVisible.value = false
      selectedFile.value = null
      filePreviewUrl.value = ''
      mediaDescription.value = ''
      uploadStatus.value = {
        type: '',
        message: ''
      }
      
      // 清除文件输入
      const fileInput = document.getElementById('media-file')
      if (fileInput) {
        fileInput.value = ''
      }
    }

    // 显示上一页
    const showPreviousInfluencerPage = () => {
      if (currentPage.value > 1 && !loading.value) {
        currentPage.value--
        loadInfluencerTrails()
      }
    }

    // 显示下一页
    const showNextInfluencerPage = () => {
      if (currentPage.value < totalPages.value && !loading.value) {
        currentPage.value++
        loadInfluencerTrails()
      }
    }

    // 切换达人足迹面板显示/隐藏
    const toggleInfluencerTrail = () => {
      if (props.controlsHidden) {
        console.log('控制栏已隐藏，无法独立控制达人足迹面板显示')
        return
      }

      isActive.value = !isActive.value
      
      if (isActive.value && props.pointId) {
        // 显示面板时，重置页码并加载数据
        loadInfluencerTrails(true)
      }
    }

    // 监听VR点变化
    watch(() => props.pointId, (newPointId) => {
      if (newPointId && isActive.value) {
        // 当VR点变化时，重新加载达人足迹
        loadInfluencerTrails(true)
      }
    })

    // 监听控制栏状态变化
    watch(() => props.controlsHidden, (hidden) => {
      if (hidden) {
        // 控制栏隐藏时，不显示达人足迹面板
        isActive.value = false
      }
    })

    // 初始化达人足迹功能
    const initInfluencerTrailFeature = () => {
      // 初始化时设置为隐藏
      isActive.value = false
      
      // 如果有pointId，加载数据
      if (props.pointId) {
        loadInfluencerTrails(true)
      }
    }

    // 初始化时设置
    onMounted(() => {
      initInfluencerTrailFeature()
      
      // 挂载到全局，以便在需要时通过window访问
      window.toggleInfluencerTrail = toggleInfluencerTrail
      window.initInfluencerTrailFeature = initInfluencerTrailFeature
    })

    return {
      isActive,
      influencerTrails,
      currentPage,
      pageSize,
      totalItems,
      totalPages,
      loading,
      uploadModalVisible,
      selectedFile,
      filePreviewUrl,
      mediaDescription,
      uploading,
      uploadStatus,
      isImageFile,
      isVideoFile,
      formatTime,
      toggleInfluencerTrail,
      loadInfluencerTrails,
      showPreviousInfluencerPage,
      showNextInfluencerPage,
      showUploadModal,
      hideUploadModal,
      handleFileSelection,
      handleUploadSubmit
    }
  }
}
</script>

<style>
/* 这里使用的是全局样式，组件内部样式已在全局CSS中定义 */

/* 视频媒体项目样式 */
.influencer-media-item.video {
  height: 200px;
}

.influencer-media-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

/* 加载容器样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: white;
}

/* 空状态容器样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: white;
  text-align: center;
}

/* 预览样式 */
.file-preview {
  margin-top: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.preview-image,
.preview-video {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

/* 上传模态框标题栏 */
.upload-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 分页按钮样式 */
.influencer-page-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.influencer-page-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
}

.influencer-page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 分页信息样式 */
.influencer-page-info {
  color: white;
  margin: 0 16px;
  font-size: 14px;
}
</style>